package com.lepu.app.main.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.app.config.AppConfig;
import com.app.config.UserConfig;
import com.app.utils.AppEnterTongJi;
import com.app.utils.Const;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.MyNetUtil;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnScrollListener;
import com.core.lib.widget.MenuBarView;
import com.core.lib.widget.MenuBarView.OnMenuBarListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.activity.IndexMyMoreArticleListActivity;
import com.lepu.app.fun.index.adapter.IndexHotArticleAdapter;
import com.lepu.app.fun.index.adapter.IndexHotArticleXieLieAdapter;
import com.lepu.app.fun.index.adapter.IndexHotTopicAdapter;
import com.lepu.app.fun.index.adapter.IndexToolAdapter;
import com.lepu.app.fun.index.bean.BeanIndex;
import com.lepu.app.fun.index.bean.BeanTool;
import com.lepu.app.fun.knowledge.bean.Article;
import com.lepu.app.fun.my.MessageAllActivity;
import com.lepu.app.fun.my.MySearchActivity;
import com.lepu.app.fun.my.PubContentDetailActivity;
import com.lepu.app.fun.my.bean.BeanMessage;
import com.lepu.app.fun.my.bean.BeanMessageCount;
import com.lepu.app.fun.my.bean.BeanPubContent;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.widget.FocusView;
import com.lepu.app.widget.GridViewForScrollview;
import com.lepu.app.widget.ListViewForScrollview;

public class MainTabFragmentIndexNew extends BaseFragment implements
		AsyncRequest, OnRefreshListener, OnLoadListener, OnScrollListener,
		OnMenuBarListener {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";
	private static final String REQUEST_MSG = "request_msg";
	private static final String REQUEST_MSG_SYSTEM = "request_msg_system";

	private static final int MSG_DATA_SUCCESS = 10;

	private static final int MSG_DATA_MORE_SUCCESS = 20;
	private static final int MSG_DATA_MORE_FAIL = 21;

	private View mView = null;
	private boolean mInitDataSuccess = false;// 是否加载完数据

	private static MainTabFragmentIndexNew instance;

	LinearLayout mBeiYunLayout;
	LinearLayout mYunQiLayout;
	LinearLayout mYueZiLayout;
	LinearLayout mYuErLayout;

	private FocusView mFocusViewTop = null;
	private FocusView mFocusViewWriter = null;

	private IndexHotTopicAdapter mHotTopicAdapter;
	private ArrayList<BeanPubContent> mHotTopicList;
	private ArrayList<BeanPubContent> mHotTopicListBeiYun;
	private ArrayList<BeanPubContent> mHotTopicListYunQi;
	private ArrayList<BeanPubContent> mHotTopicListYueZi;
	private ArrayList<BeanPubContent> mHotTopicListYuEr;

	BeanIndex mBeanIndex;
	BeanIndex mBeanIndexBeiYun;
	BeanIndex mBeanIndexYunQi;
	BeanIndex mBeanIndexYueZi;
	BeanIndex mBeanIndexYuEr;

	private int mCurrentPageBeiYun = 1;
	private int mCurrentPageYunQi = 1;
	private int mCurrentPageYueZi = 1;
	private int mCurrentPageYuEr = 1;

	private String mRefreshTimeBeiYun = "";
	private String mRefreshTimeYunQi = "";
	private String mRefreshTimeYueZi = "";
	private String mRefreshTimeYuEr = "";

	private FrameLayout mContentLayout = null;
	private View mContentTopView = null;
	private LinearLayout mTopbarLayout = null;
	private ImageView mSearchBgImageView = null;
	private MenuBarView mLeftTopTabLayout = null;
	private TextView mMainTopMessageTextView = null;

	// ==================================
	private int mCurrentTab = 3;// 初始化月子tab
	private int mCurrentPage = 1;
	private String mRefreshTime = "";

	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private View mHeaderViewTop = null;
	private View mHeaderViewCenter = null;

	private boolean mScrollStop = false;

	private BeanMessageCount mBeanMsg; // 消息bean

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mView = LayoutInflater.from(getActivity()).inflate(
				R.layout.app_fragment_list_layout, null, false);
		instance = this;
		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mFocusViewTop != null) {
			mFocusViewTop.onResumeViewPager();
		}

		if (mFocusViewWriter != null) {
			mFocusViewWriter.onResumeViewPager();
		}

		// 请求消息数量接口
		requestAlarm();
		UmengHelper.OnPageStart("2");
	}

	@Override
	public void onPause() {
		super.onPause();

		if (mFocusViewTop != null) {
			mFocusViewTop.onPauseViewPager();
		}

		if (mFocusViewWriter != null) {
			mFocusViewWriter.onPauseViewPager();
		}

		UmengHelper.OnPageEnd("2");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		return mContentLayout;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		instance = null;
		mInitDataSuccess = false;
	}

	public static MainTabFragmentIndexNew getInstance() {
		return instance;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				// 第一次进入页面获取数据

			}
		}
	}

	@SuppressLint("InflateParams")
	@SuppressWarnings("deprecation")
	private void init() {

		mContentLayout = new FrameLayout(getActivity());

		mDataListView = (ListView) mView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mView
				.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setOnScrollListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				R.color.color_listview_refresh_2,
				R.color.color_listview_refresh_3,
				R.color.color_listview_refresh_4);

		mHeaderViewTop = LayoutInflater.from(getActivity()).inflate(
				R.layout.main_tab_fragment_index_new_header, null);
		mHeaderViewCenter = LayoutInflater.from(getActivity()).inflate(
				R.layout.main_tab_fragment_index_new_footer, null);

		mBeiYunLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.beiYunLayout);
		mYunQiLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.yunQiLayout);
		mYueZiLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.yueZiLayout);
		mYuErLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.yuErLayout);

		TextView moreArticleTextView = (TextView) mHeaderViewCenter
				.findViewById(R.id.moreArticleTextView);
		TextView moreTopicTextView = (TextView) mHeaderViewCenter
				.findViewById(R.id.moreTopicTextView);

		mBeiYunLayout.setOnClickListener(mOnClickListener);
		mYunQiLayout.setOnClickListener(mOnClickListener);
		mYueZiLayout.setOnClickListener(mOnClickListener);
		mYuErLayout.setOnClickListener(mOnClickListener);

		moreArticleTextView.setOnClickListener(mOnClickListener);
		moreTopicTextView.setOnClickListener(mOnClickListener);

		// 第一次加载数据
		mCurrentTab = UserConfig.getConfigInt(getActivity(),
				Const.CONFIG_APP_INDEX_TAB_INDEX, 3);

		initTop();
		// showFirstLoadDataLayout(true);
		mLeftTopTabLayout.setSelectedIndex(mCurrentTab - 1);

		mDataListView.addHeaderView(mHeaderViewTop);
		mDataListView.addHeaderView(mHeaderViewCenter);
		mDataListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				if (position < 2) {
					return;
				}

				BeanPubContent item = mHotTopicList.get(position - 2);

				Intent intent = new Intent(getActivity(),
						PubContentDetailActivity.class);
				intent.putExtra("tag", 1);
				intent.putExtra("TopicId", item.TopicID);

				if (item.IsGood == 1) { // 精华
					intent.putExtra("nameType", 2);
				}

				MainTabActivity.getInstance().startActivity(intent, true);
			}
		});

		mContentLayout.addView(mView);

		// 滚动到顶部
		upTop();

	}

	@SuppressLint("InflateParams")
	private void initTop() {

		mContentTopView = LayoutInflater.from(getActivity()).inflate(
				R.layout.index_main_top_layout, null);
		mMainTopMessageTextView = (TextView) mContentTopView
				.findViewById(R.id.mainTopMessageTextView);

		FrameLayout alarmFrameLayout = (FrameLayout) mContentTopView
				.findViewById(R.id.alarmFrameLayout);
		mSearchBgImageView = (ImageView) mContentTopView
				.findViewById(R.id.searchBgImageView);
		mSearchBgImageView.setBackgroundColor(Color.argb(70, 0, 0, 0));
		mTopbarLayout = (LinearLayout) mContentTopView
				.findViewById(R.id.topbarLayout);
		mLeftTopTabLayout = (MenuBarView) mContentTopView
				.findViewById(R.id.leftTopTabLayout);
		mLeftTopTabLayout.setVisibility(View.GONE);
		mLeftTopTabLayout.setOnMenuBarListener(this);

		alarmFrameLayout.setOnClickListener(mOnClickListener);
		mSearchBgImageView.setOnClickListener(mOnClickListener);
	}

	/**
	 * 
	 * @param beanIndex
	 */
	private void initData(BeanIndex beanIndex) {

		if (mContentLayout.getChildCount() < 2) {
			mContentLayout.addView(mContentTopView);
		}

		//更新顶部状态栏
		upToolTop();
		showFirstLoadDataLayout(false);
		//MainTabActivity.getInstance().hideProgressDialog();
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mGoogleRefreshLayout.setRefreshing(false);
			}
		}, 100);

		ArrayList<Article> BannerList = null;

		if (beanIndex != null) {

			// 网络数据加载成功
			mInitDataSuccess = true;

			// 顶部banner
			BannerList = beanIndex.BannerList;

			// 今日热帖
			mHotTopicList = beanIndex.HotTopicList;
		}

		// top banner
		int topBannerSize = 0;
		if(mBeanIndex != null && mBeanIndex.BannerList != null)
		{
			topBannerSize = mBeanIndex.BannerList.size();
		}

		if (topBannerSize == 0 || mFocusViewTop == null) {
			mFocusViewTop = new FocusView(getActivity(), BannerList,
					Utils.getBannerHeight16To9(getActivity()), null,
					R.drawable.index_banner_icon_default,
					R.drawable.index_banner_icon_default,mGoogleRefreshLayout);
			LinearLayout topFocusLayout = (LinearLayout) mHeaderViewTop
					.findViewById(R.id.topFocusLayout);
			topFocusLayout.removeAllViews();
			topFocusLayout.addView(mFocusViewTop);
		}

		mBeanIndex = beanIndex;
		initHeaderData();

		// =======================================
		mHotTopicAdapter = new IndexHotTopicAdapter(getActivity(),
				mHotTopicList);
		mDataListView.setAdapter(mHotTopicAdapter);

		if (mHotTopicList != null && mHotTopicList.size() > 0) {
			mRefreshTime = mHotTopicList.get(mHotTopicList.size() - 1).SortWeight;

			if (mHotTopicList.size() < Setting.PAGE_SIZE) {
				mGoogleRefreshLayout.setLoadMoreFinish(true);
			}
		}else{
			mGoogleRefreshLayout.setLoadMoreFinish(true);
		}
		
		setTabData(beanIndex);
	}

	private void initHeaderData() {
		
		if (mBeanIndex == null) {
			return;
		}

		// 系列文章
		final ArrayList<Article> SeriesList = mBeanIndex.SeriesList;

		IndexHotArticleXieLieAdapter xieLieAdapter = new IndexHotArticleXieLieAdapter(
				getActivity(), SeriesList);
		ListViewForScrollview xiLieArticleListView = (ListViewForScrollview) mHeaderViewCenter
				.findViewById(R.id.xiLieArticleListView);
		xiLieArticleListView.setAdapter(xieLieAdapter);
		xiLieArticleListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Article item = SeriesList.get(position);

				MyNetUtil.getInstance().requestArticleDetail(
						MainTabActivity.getInstance(), item.ArticleID, "2",
						item.ContentType, item.ArticleTag);
			}
		});

		// 每日关注
		final ArrayList<Article> DayArticleList = mBeanIndex.DayArticleList;
		IndexHotArticleAdapter articleAdapter = new IndexHotArticleAdapter(
				getActivity(), DayArticleList);
		ListViewForScrollview articleListView = (ListViewForScrollview) mHeaderViewCenter
				.findViewById(R.id.articleListView);
		articleListView.setAdapter(articleAdapter);
		articleListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Article item = DayArticleList.get(position);

				MyNetUtil.getInstance().requestArticleDetail(
						MainTabActivity.getInstance(), item.ArticleID,
						item.DisplayType, item.ContentType, "");
			}
		});

		// 作家专栏banner
		mFocusViewWriter = new FocusView(getActivity(), mBeanIndex.AuthorList,
				Utils.getBannerHeight16To9(getActivity()), null, 0,
				R.drawable.app_icon_defaut_16_9,mGoogleRefreshLayout);
		LinearLayout writerFocusLayout = (LinearLayout) mHeaderViewCenter
				.findViewById(R.id.writerFocusLayout);
		writerFocusLayout.removeAllViews();
		writerFocusLayout.addView(mFocusViewWriter);
	}

	@SuppressWarnings("unused")
	private void showHideNoDataLayout(boolean isShow) {
		LinearLayout noDataLayout = (LinearLayout) mView
				.findViewById(R.id.noDataLayout);
		if (noDataLayout != null) {
			if (isShow) {
				noDataLayout.setVisibility(View.VISIBLE);
			} else {
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}

	private void showFirstLoadDataLayout(boolean isShow) {
		LinearLayout firstLoadDataLayout = (LinearLayout) mView
				.findViewById(R.id.firstLoadDataLayout);
		if (firstLoadDataLayout != null) {
			if (isShow) {
				firstLoadDataLayout.setVisibility(View.VISIBLE);

				LinearLayout noDataLayout = (LinearLayout) mView
						.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
			} else {
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 更新消息
	 */
	public void updateMessage(BeanMessageCount beanMessage) {
		if (mMainTopMessageTextView != null) {
			int count = beanMessage.motherCount + beanMessage.phoneCount
					+ beanMessage.writerCount + beanMessage.friendCount
					+ beanMessage.systemCount;// 应从数据库获取，可能。具体再说
			if (count > 0) {
				mMainTopMessageTextView.setText(String.valueOf(count));
				mMainTopMessageTextView.setVisibility(View.VISIBLE);
			} else {
				mMainTopMessageTextView.setVisibility(View.GONE);
			}
		}
	}

	private void initTool() {
		GridViewForScrollview toolGridView = (GridViewForScrollview) mHeaderViewCenter
				.findViewById(R.id.toolGridView);
		List<BeanTool> dataList = null;
		if (mCurrentTab == 1) {
			dataList = BeanTool.getToolBeiYun();
		} else if (mCurrentTab == 2) {
			dataList = BeanTool.getToolYunQi();
		} else if (mCurrentTab == 3) {
			dataList = BeanTool.getToolYueZi();
		} else {
			dataList = BeanTool.getToolYuEr();
		}
		toolGridView.setNumColumns(4);
		IndexToolAdapter toolAdapter = new IndexToolAdapter(getActivity(),
				dataList);
		toolGridView.setAdapter(toolAdapter);
	}

	private void updateToolState() {
		mBeiYunLayout.setSelected(false);
		mYunQiLayout.setSelected(false);
		mYueZiLayout.setSelected(false);
		mYuErLayout.setSelected(false);

		if (mCurrentTab == 1) {
			mBeiYunLayout.setSelected(true);
		} else if (mCurrentTab == 2) {
			mYunQiLayout.setSelected(true);
		} else if (mCurrentTab == 3) {
			mYueZiLayout.setSelected(true);
		} else {
			mYuErLayout.setSelected(true);
		}

		UserConfig.setConfig(getActivity(), Const.CONFIG_APP_INDEX_TAB_INDEX,
				mCurrentTab);
	}

	private void upTop() {
		mDataListView.scrollTo(0, 0);
	}

	@SuppressLint("NewApi")
	private void upToolTop() {

		if (mLeftTopTabLayout.getVisibility() == View.VISIBLE) {
			// LinearLayout topFocusLayout = (LinearLayout) mHeaderViewTop
			// .findViewById(R.id.topFocusLayout);
			// LinearLayout tabBarLayout = (LinearLayout) mHeaderViewTop
			// .findViewById(R.id.tabBarLayout);
			// // 没必要减去这个toolbar的高度，奇怪，暂时先这样
			// LinearLayout toolBarLayout = (LinearLayout) mHeaderViewCenter
			// .findViewById(R.id.toolBarLayout);
			//
			// int topbarHeight = topFocusLayout.getHeight()
			// + tabBarLayout.getHeight() + mTopbarLayout.getHeight()
			// - toolBarLayout.getHeight() - 20;
			//
			// mDataListView.scrollTo(0, topbarHeight);

			// mDataListView.scrollTo(0, mScroolOffsetY);

			//
			mLeftTopTabLayout.setVisibility(View.GONE);
			mTopbarLayout.setBackgroundResource(R.color.color_transparent);
			mSearchBgImageView.setVisibility(View.VISIBLE);
			mSearchBgImageView.setBackgroundColor(Color.argb(70, 0, 0, 0));
		}
	}

	/**
	 * 请求首页数据
	 */
	public void request(boolean isMore) {

		if(getActivity() == null)
		{
			return;
		}

		String request = "";
		String url = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
			url = Setting.getIndexMoreUrl();
		} else {
			//MainTabActivity.getInstance().showProgressDialog();

			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
				}
			}, 100);

			request = REQUEST_DATA;
			mRefreshTime = "";
			mCurrentPage = page;
			url = Setting.getIndexUrl();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			params.put("Period", mCurrentTab);

			if (isMore) {
				params.put("RefreshSortWeight", mRefreshTime);
				params.put("PageIndex", page);
				params.put("PageSize", Setting.PAGE_SIZE);

			} else {
				params.put("PageSize", Setting.PAGE_SIZE);
				String version = getActivity().getPackageManager()
						.getPackageInfo(getActivity().getPackageName(), 0).versionName;
				params.put("ClientVersion", version);

			}
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post(url, map, null, this, request, true, false, true);
	}

	/**
	 * 请求消息
	 */
	private void requestAlarm() {
		//请求前初始化(不初始化请求失败的话之前的消息数量还在)
		mBeanMsg = new BeanMessageCount();
		
		if (!LoginUtil.checkIsLogin()) {
			//没登陆直接请求系统消息
			requestSystemAlarm();
			return;
		}

		String url = Setting.getMassegeCountUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG, true);
	}
	/**
	 * 请求系统消息
	 */
	private void requestSystemAlarm() {
		
		String url = Setting.getSystemDataUrl();
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("MessageType", 1);
			params.put("AppChannel", UtilityBase.getAppMetedata(getActivity(),"UMENG_CHANNEL")); //渠道来源
			params.put("AppVersion", AppManager.getAppVersionName(getActivity())); //app版本
			long useTimeMill = DateUtil.getNowTimeInMillis() - AppConfig.getConfigLong(getActivity(), Const.CONFIG_APP_USE_TIME, DateUtil.getNowTimeInMillis());
			int useDays = ((int) (useTimeMill/DateUtil.DAY_MILLIS))+1;
			params.put("DaysInAPP", useDays); //使用天数
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG_SYSTEM, true);
	}

	View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.beiYunLayout:
				AppEnterTongJi.clickEvent(29, "");

				mCurrentTab = 1;
				updateToolState();
				mLeftTopTabLayout.setSelectedIndex(mCurrentTab - 1);

				break;
			case R.id.yunQiLayout:
				AppEnterTongJi.clickEvent(30, "");

				mCurrentTab = 2;
				updateToolState();
				mLeftTopTabLayout.setSelectedIndex(mCurrentTab - 1);

				break;
			case R.id.yueZiLayout:
				AppEnterTongJi.clickEvent(31, "");

				mCurrentTab = 3;
				updateToolState();
				mLeftTopTabLayout.setSelectedIndex(mCurrentTab - 1);

				break;
			case R.id.yuErLayout:
				AppEnterTongJi.clickEvent(32, "");

				mCurrentTab = 4;
				updateToolState();
				mLeftTopTabLayout.setSelectedIndex(mCurrentTab - 1);

				break;
			case R.id.alarmFrameLayout:
				AppEnterTongJi.clickEvent(28, "");
				
				Intent intentMessage = new Intent(getActivity(),MessageAllActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("beanMsg", mBeanMsg);
				intentMessage.putExtras(bundle);

				MainTabActivity.getInstance()
						.startActivity(intentMessage, true);
				break;
			case R.id.searchBgImageView:
				// 搜索
				AppEnterTongJi.clickEvent(26, "");

				Intent intentSearch = new Intent(getActivity(),
						MySearchActivity.class);
				intentSearch.putExtra("type", MySearchActivity.TYPE_ALL);
				MainTabActivity.getInstance().startActivity(intentSearch, true);
				break;
			case R.id.moreArticleTextView:
				// 更多文章
				AppEnterTongJi.clickEvent(33, "");

				Intent intentArticleList = new Intent(getActivity(),
						IndexMyMoreArticleListActivity.class);
				intentArticleList.putExtra("Period", mCurrentTab);
				MainTabActivity.getInstance().startActivity(intentArticleList,
						true);
				break;
			case R.id.moreTopicTextView:
				// 更多热帖
				AppEnterTongJi.clickEvent(34, "");

				MainTabActivity.getInstance().setMenuTab(2);
				break;

			default:
				break;
			}
		}
	};

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				initData((BeanIndex) msg.obj);
				
				break;
			case MSG_DATA_MORE_SUCCESS:
				mGoogleRefreshLayout.setLoading(false);

				@SuppressWarnings("unchecked")
				ArrayList<BeanPubContent> dataMoreList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mHotTopicAdapter.notifyDataSetChanged();
					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(getActivity(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				setTabData(null);
				break;
			case MSG_DATA_MORE_FAIL:

				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {

			BeanIndex beanIndex = BeanIndex.parseJsonData((String) data);

			// test
			// beanIndex = BeanIndex.getTestData();

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = beanIndex;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {

			ArrayList<BeanPubContent> dataMoreArraylist = BeanPubContent
					.parseJsonData((String) data);

			// test
			// dataMoreArraylist = BeanPubContent.getTestData();

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mRefreshTime = dataMoreArraylist
						.get(dataMoreArraylist.size() - 1).SortWeight;

				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					BeanPubContent item = dataMoreArraylist.get(i);
					mHotTopicList.add(item);
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_MSG)) {
			mBeanMsg = BeanMessageCount.parseJsonData((String) data);
			updateMessage(mBeanMsg);
			//请求系统消息
			requestSystemAlarm();
		}else if (object.equals(REQUEST_MSG_SYSTEM)) {
			ArrayList<BeanMessage> beanList = BeanMessage.parseJsonSystemData((String)data);
			if(beanList != null){
				for(BeanMessage item : beanList)
				{
					item.Board = 4;
					item.IsRead = 0;
					item.LoginUserID = LoginUtil.getUserId();
					
					if(!BeanMessage.getMsgIsExist(item.LoginUserID, 4, item.IMID)){
						BeanMessage.insertMyMessage(item);
					}
				}
				
				int msgCount = BeanMessage.getNewMessageCount(LoginUtil.getUserId(), 4);
				
				mBeanMsg.systemCount = mBeanMsg.systemCount+msgCount;
				updateMessage(mBeanMsg);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_SUCCESS);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}else if(object.equals(REQUEST_MSG)){
			//及时更新消息状态
			updateMessage(mBeanMsg);
			//请求系统消息
			requestSystemAlarm();
		}else if(object.equals(REQUEST_MSG_SYSTEM)){
			int msgCount = BeanMessage.getNewMessageCount(LoginUtil.getUserId(), 4);
			
			mBeanMsg.systemCount = mBeanMsg.systemCount+msgCount;
			//及时更新消息状态
			updateMessage(mBeanMsg);
		}
	}

	public void clearMemoryCacheDataAndRequestData()
	{
		mHotTopicList = null;
		mHotTopicListBeiYun = null;
		mHotTopicListYunQi = null;
		mHotTopicListYueZi = null;
		mHotTopicListYuEr = null;

		mBeanIndex = null;
		mBeanIndexBeiYun = null;
		mBeanIndexYunQi = null;
		mBeanIndexYueZi = null;
		mBeanIndexYuEr = null;

		mCurrentPageBeiYun = 1;
		mCurrentPageYunQi = 1;
		mCurrentPageYueZi = 1;
		mCurrentPageYuEr = 1;

		mRefreshTimeBeiYun = "";
		mRefreshTimeYunQi = "";
		mRefreshTimeYueZi = "";
		mRefreshTimeYuEr = "";

		request(false);
	}

	@Override
	public void onMenuBarItemSelected(int menuIndex,View view) {

		if (MainTabActivity.getInstance() == null) {
			return;
		}

		mCurrentTab = menuIndex + 1;
		updateToolState();
		initTool();

		boolean flagRequest = true;
		if (mCurrentTab == 1) {
			if (mHotTopicListBeiYun != null && mHotTopicListBeiYun.size() > 0) {
				
				mBeanIndex = mBeanIndexBeiYun;
				initHeaderData();
				
				mHotTopicList.clear();
				mHotTopicList.addAll(mHotTopicListBeiYun);
				mHotTopicAdapter.notifyDataSetChanged();

				flagRequest = false;
			}
			mCurrentPage = mCurrentPageBeiYun;
			mRefreshTime = mRefreshTimeBeiYun;
		} else if (mCurrentTab == 2) {
			if (mHotTopicListYunQi != null && mHotTopicListYunQi.size() > 0) {
				
				mBeanIndex = mBeanIndexYunQi;
				initHeaderData();
				
				mHotTopicList.clear();
				mHotTopicList.addAll(mHotTopicListYunQi);
				mHotTopicAdapter.notifyDataSetChanged();

				flagRequest = false;
			}
			mCurrentPage = mCurrentPageYunQi;
			mRefreshTime = mRefreshTimeYunQi;
		} else if (mCurrentTab == 3) {
			if (mHotTopicListYueZi != null && mHotTopicListYueZi.size() > 0) {
				
				mBeanIndex = mBeanIndexYueZi;
				initHeaderData();
				
				mHotTopicList.clear();
				mHotTopicList.addAll(mHotTopicListYueZi);
				mHotTopicAdapter.notifyDataSetChanged();

				flagRequest = false;
			}
			mCurrentPage = mCurrentPageYueZi;
			mRefreshTime = mRefreshTimeYueZi;
		} else if (mCurrentTab == 4) {
			if (mHotTopicListYuEr != null && mHotTopicListYuEr.size() > 0) {
				
				mBeanIndex = mBeanIndexYuEr;
				initHeaderData();
				
				mHotTopicList.clear();
				mHotTopicList.addAll(mHotTopicListYuEr);
				mHotTopicAdapter.notifyDataSetChanged();

				flagRequest = false;
			}
			mCurrentPage = mCurrentPageYuEr;
			mRefreshTime = mRefreshTimeYuEr;
		}

		// 只要切换tab，允许加载更多
		mGoogleRefreshLayout.setLoadMoreFinish(false);

		if (flagRequest) {
			//upToolTop();
			request(false);
		}

	}

	private void setTabData(BeanIndex beanIndex) {

		if(mHotTopicList == null)
		{
			mHotTopicList = new ArrayList<BeanPubContent>();
		}
		if (mCurrentTab == 1) {
			if (mHotTopicListBeiYun == null) {
				mHotTopicListBeiYun = new ArrayList<BeanPubContent>();
			} else {
				mHotTopicListBeiYun.clear();
			}

			mHotTopicListBeiYun.addAll(mHotTopicList);

			mCurrentPageBeiYun = mCurrentPage;
			mRefreshTimeBeiYun = mRefreshTime;
			
			if(beanIndex == null)
			{
				return;
			}
			mBeanIndexBeiYun = beanIndex;

		} else if (mCurrentTab == 2) {
			if (mHotTopicListYunQi == null) {
				mHotTopicListYunQi = new ArrayList<BeanPubContent>();
			} else {
				mHotTopicListYunQi.clear();
			}

			mHotTopicListYunQi.addAll(mHotTopicList);

			mCurrentPageYunQi = mCurrentPage;
			mRefreshTimeYunQi = mRefreshTime;
			
			if(beanIndex == null)
			{
				return;
			}
			mBeanIndexYunQi = beanIndex;

		} else if (mCurrentTab == 3) {
			if (mHotTopicListYueZi == null) {
				mHotTopicListYueZi = new ArrayList<BeanPubContent>();
			} else {
				mHotTopicListYueZi.clear();
			}

			mHotTopicListYueZi.addAll(mHotTopicList);

			mCurrentPageYueZi = mCurrentPage;
			mRefreshTimeYueZi = mRefreshTime;
			
			if(beanIndex == null)
			{
				return;
			}
			mBeanIndexYueZi = beanIndex;

		} else if (mCurrentTab == 4) {
			if (mHotTopicListYuEr == null) {
				mHotTopicListYuEr = new ArrayList<BeanPubContent>();
			} else {
				mHotTopicListYuEr.clear();
			}

			mHotTopicListYuEr.addAll(mHotTopicList);

			mCurrentPageYuEr = mCurrentPage;
			mRefreshTimeYuEr = mRefreshTime;
			
			if(beanIndex == null)
			{
				return;
			}
			mBeanIndexYuEr = beanIndex;
		}
	}

	@Override
	public void onLoad() {

		if(mBeanIndex == null)
		{
			mGoogleRefreshLayout.setLoading(false);
			return;
		}
		AppEnterTongJi.clickEvent(35, "");
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// LogUtilBase.LogD(null, "index onScrollStateChanged");

		// 第1次：scrollState = SCROLL_STATE_TOUCH_SCROLL(1) 正在滚动
		// 第2次：scrollState = SCROLL_STATE_FLING(2) 手指做了抛的动作（手指离开屏幕前，用力滑了一下）
		// 第3次：scrollState = SCROLL_STATE_IDLE(0) 停止滚动

		if (scrollState == 0) {
			mScrollStop = true;
		} else {
			mScrollStop = false;
		}

	}

	private int getScrollY() {
		View c = mDataListView.getChildAt(0);
		if (c == null) {
			return 0;
		}
		int firstVisiblePosition = mDataListView.getFirstVisiblePosition();
		int top = c.getTop();
		return -top + firstVisiblePosition * c.getHeight();
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		if (mScrollStop) {
			return;
		}

		if (mHeaderViewTop == null) {
			return;
		}

		LinearLayout topFocusLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.topFocusLayout);
		LinearLayout tabBarLayout = (LinearLayout) mHeaderViewTop
				.findViewById(R.id.tabBarLayout);
		// 没必要减去这个toolbar的高度，奇怪，暂时先这样
//		LinearLayout toolBarLayout = (LinearLayout) mHeaderViewCenter
//				.findViewById(R.id.toolBarLayout);

		int statusBarHeight = Utils.getStatusBarHeight(getActivity());
		int topHeight = topFocusLayout.getHeight() + statusBarHeight*2;
		//+ tabBarLayout.getHeight() + mTopbarLayout.getHeight() - toolBarLayout.getHeight() - 20

		int t = getScrollY();

		// 从无到有 255-alpha
		int alphaTopbar = (t >= topHeight ? 0 : (topHeight - t) * 255
				/ topHeight);

		if(firstVisibleItem > 1)
		{
			mTopbarLayout.setBackgroundColor(Color.argb(255, 243, 71,
					112));
		}else{
			mTopbarLayout.setBackgroundColor(Color.argb(255 - alphaTopbar, 243, 71,
					112));
		}

		// 从有到无 alpha
		int alphaSearch = (t >= topHeight ? 0 : (topHeight - t) * 255
				/ topHeight);
		if (alphaSearch > 70) {
			alphaSearch = 70;
		}

		if(firstVisibleItem > 1)
		{
			mSearchBgImageView.setBackgroundColor(Color.argb(0, 0, 0, 0));
		}else{
			mSearchBgImageView.setBackgroundColor(Color.argb(alphaSearch, 0, 0, 0));
		}

		if (t > topHeight) {
			mLeftTopTabLayout.setVisibility(View.VISIBLE);
		} else {
			if(firstVisibleItem > 1)
			{
				mLeftTopTabLayout.setVisibility(View.VISIBLE);
			}else{
				mLeftTopTabLayout.setVisibility(View.GONE);
			}
		}
	}
}
